﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WFNetLib.MyControls;
using System.Data.OleDb;
using System.IO;

namespace 自消费
{
    public partial class 任务设置 : Form
    {
        public 任务设置()
        {
            InitializeComponent();
        }
        bool bSetEnabled;
        private void 任务设置_Load(object sender, EventArgs e)
        {           
            DataTable dt = WFNetLib.ADO.AccessOP.DataTableSQL("select * from taskgroup");
            toolStripComboBox1.Items.Clear();
            int index = 0;
            foreach (DataRow dr in dt.Rows)
            {
                ComboBoxItem group=new ComboBoxItem(dr["groupname"].ToString(),dr["ID"].ToString());
                int x=toolStripComboBox1.Items.Add(group); 
                if(group.ToString()=="默认分组")
                    index = x;
            }
            toolStripComboBox1.SelectedIndex = index;
            LoadTask();
            SetUA(comboBox1);
        }
        void LoadTask()
        {
            bSetEnabled = false;
            listView1.Items.Clear();
            ComboBoxItem group = (ComboBoxItem)toolStripComboBox1.Items[toolStripComboBox1.SelectedIndex];
            OleDbDataReader reader = WFNetLib.ADO.AccessOP.ReaderExecuteSQL("select * from task where taskgroup_id="+group.Value.ToString()+" order by seqnum");
            while (reader.Read())
            {
                TaskData td = TaskDataFactory.Construct(reader);
                ListViewItem lvi = listView1.Items.Add(td.seqnum.ToString());
                lvi.Tag = td;
                lvi.SubItems.Add(td.taskname);
                lvi.SubItems.Add(Enum.GetName(typeof(taskType), td.type));
                lvi.SubItems.Add(td.RunTimes.ToString());
                lvi.SubItems.Add(td.IntervalTime.ToString());
                if (!td.enabled)
                    lvi.Checked = false;
                else
                    lvi.Checked = true;
            }            
            bSetEnabled = true;
            reader.Close();
        }
        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedIndex)
            {
                case 0:
                    SetTask0("insert");
                    break;
            }            
        }
        void SetTask0(string sqltype, int index)
        {
            int seqnum = 1;
            if (textBox1.Text == "")
            {
                MessageBox.Show("任务名称不能为空");
                return;
            }
            if (textBox7.Text == "")
            {
                MessageBox.Show("链接地址不能为空");
                return;
            }
            if (comboBox1.Text == "")
            {
                MessageBox.Show("ua不能为空");
                return;
            }
            if(sqltype=="insert")
            {
                foreach (ListViewItem lvi in listView1.Items)
                {
                    if (lvi.SubItems[1].Text == textBox1.Text)//检查任务名称是否重复
                    {
                        MessageBox.Show("已经存在相同的任务名称！！！");
                        return;
                    }
                    if (Convert.ToInt32(lvi.SubItems[0].Text) >= seqnum)
                        seqnum++;
                }
            }
            TaskData td = new TaskData();
            td.seqnum = seqnum;
            ComboBoxItem group = (ComboBoxItem)toolStripComboBox1.Items[toolStripComboBox1.SelectedIndex];
            td.taskgroup_id = Convert.ToInt32(group.Value);
            td.taskname = textBox1.Text;
            td.type = 1;
            td.content = textBox2.Text + "||" + textBox5.Text + "||" + textBox7.Text + "||" + comboBox1.Text + "||" + numericUpDown1.Value.ToString();
            if (sqltype == "insert")
            {
                if(TaskDataDBOption.Insert(td)==1)
                {
                    MessageBox.Show("添加成功");
                    LoadTask();
                }
                else
                    MessageBox.Show("操作失败");

            }
            else if (sqltype == "update")
            {
                ListViewItem lvi = listView1.Items[index];
                td.ID = ((TaskData)lvi.Tag).ID;
                td.enabled = lvi.Checked;
                td.seqnum = Convert.ToInt32(lvi.SubItems[0].Text);
                if (TaskDataDBOption.Update(td) == 1)
                {
                    MessageBox.Show("修改成功");
                    bSetEnabled = false;
                    lvi.Tag = td;
                    lvi.SubItems[1].Text = textBox1.Text;
                    lvi.SubItems.Add(textBox1.Text);
                    lvi.SubItems[2].Text = Enum.GetName(typeof(taskType), 1);
                    bSetEnabled = true;
                }
            }                
        }
        void SetTask0(string sqltype)
        {
            SetTask0(sqltype, 0);
        }

        private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (!bSetEnabled)
                return;
            TaskData td = (TaskData)e.Item.Tag;
            string sql = "update task set enabled="+Convert.ToInt16(e.Item.Checked)+" where id="+td.ID.ToString();
            if (WFNetLib.ADO.AccessOP.NonQuerySQL(sql) != 1)
            {
                MessageBox.Show("修改失败");
            }
            else
            {
                td.enabled = e.Item.Checked;
                e.Item.Tag = td;
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
            {
                foreach (ListViewItem lvi1 in listView1.Items)
                {
                    lvi1.BackColor = SystemColors.Window;
                }
                return;
            }
            ListViewItem lvi = listView1.SelectedItems[0];
            lvi.BackColor = Color.BlueViolet;
            OleDbDataReader reader = WFNetLib.ADO.AccessOP.ReaderExecuteSQL("select * from task where id=" + ((TaskData)lvi.Tag).ID.ToString());
            if (!reader.Read())
            {
                reader.Close();
                return;
            }
            TaskData td = TaskDataFactory.Construct(reader);
            reader.Close();
            switch (td.type)
            {
                case 1:
                    tabControl1.SelectedIndex = 0;
                    textBox1.Text = td.taskname;
                    string[] ps = td.content.Split(new string[1]{"||"},StringSplitOptions.None);
                    textBox2.Text = ps[0];
                    textBox5.Text = ps[1];
                    textBox7.Text = ps[2];
                    comboBox1.Text = ps[3];
                    numericUpDown1.Value = Convert.ToDecimal(ps[4]);
                    break;
            }
        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
                return;
            ListViewItem lvi = listView1.SelectedItems[0];
            switch (tabControl1.SelectedIndex)
            {
                case 0:
                    SetTask0("update",lvi.Index);
                    break;
            }
        }

        private void toolStripButton12_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
            {                
                return;
            }
            if (MessageBox.Show("是否删除当前选中任务，删除后无法恢复", "警告", MessageBoxButtons.YesNo) == DialogResult.No)
                return;
            ListViewItem lvi = listView1.SelectedItems[0];
            WFNetLib.ADO.AccessOP.NonQuerySQL("delete from task where id=" + ((TaskData)lvi.Tag).ID.ToString());
            listView1.Items.RemoveAt(lvi.Index);
            MessageBox.Show("删除成功");            
        }

        private void toolStripButton13_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否删除所有任务，删除后无法恢复", "警告", MessageBoxButtons.YesNo) == DialogResult.No)
                return;
            WFNetLib.ADO.AccessOP.NonQuerySQL("delete from task");
            listView1.Items.Clear();
            MessageBox.Show("删除成功");            
        }
        void SetUA(ComboBox cb)
        {
            string strResult = "";
            FileStream fStream = new FileStream(System.Windows.Forms.Application.StartupPath + "\\UA-GSM.txt", FileMode.Open, FileAccess.Read);
            StreamReader sReader = new StreamReader(fStream, Encoding.Default);
            try
            {
                cb.Items.Clear();
                while (!sReader.EndOfStream)
                {
                    strResult = sReader.ReadLine();
                    //if(strResult[0]!='*')
                        cb.Items.Add(strResult);
                }
                //cb.SelectedIndex = 0;
            }
            catch { }
            finally
            {
                fStream.Flush();
                fStream.Close();
                sReader.Close();
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {      
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string file = openFileDialog1.FileName;
                FileStream fs = new FileStream(file, FileMode.Open);
                StreamReader sw = new StreamReader(fs);
                //开始写入
                fs.Seek(0, SeekOrigin.Begin);
                StringBuilder no=new StringBuilder();
                int count = 0;
                int seqnum = 1;
                foreach (ListViewItem lvi in listView1.Items)
                {                    
                    if (Convert.ToInt32(lvi.SubItems[0].Text) >= seqnum)
                        seqnum++;
                }
                while (!sw.EndOfStream)
                {
                    string str = sw.ReadLine();
                    string[] pa = str.Split(new string[1] { "┇┇" }, StringSplitOptions.None);
                    TaskData td = new TaskData();
                    ComboBoxItem group = (ComboBoxItem)toolStripComboBox1.Items[toolStripComboBox1.SelectedIndex];
                    td.taskname = pa[0];
                    td.taskgroup_id = Convert.ToInt32(group.Value);
                    td.content = pa[1];
                    td.enabled = Convert.ToBoolean(pa[2]);
                    td.ex_setting = pa[3];
                    td.IntervalTime = Convert.ToInt32(pa[4]);
                    td.RunTimes = Convert.ToInt32(pa[5]);
                    td.type = Convert.ToInt32(pa[6]);
                    bool bexist=false;
                    foreach (ListViewItem lvi in listView1.Items)
                    {
                        if (lvi.SubItems[1].Text == td.taskname)//检查任务名称是否重复
                        {
                            no.Append("已经任务名称:"+td.taskname+"\r\n");
                            bexist = true; ;
                            break;
                        }
                    }
                    if (bexist)
                        continue;
                    td.seqnum = seqnum;
                    seqnum++;
                    if (TaskDataDBOption.Insert(td) != 1)
                        no.Append(td.taskname + "导入失败" + "\r\n");
                    else
                        count++;
                }
                //关闭流
                sw.Close();
                fs.Close();/**/
                MessageBox.Show("成功导出" + count + "条任务");
                if (no.Length != 0)
                    MessageBox.Show("导入不成功的任务如下:\r\n" + no.ToString());
                LoadTask();
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string file = saveFileDialog1.FileName;
                FileStream fs = new FileStream(file, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入
                fs.Seek(0, SeekOrigin.End);
                foreach (ListViewItem lvi in listView1.Items)
                {
                    TaskData td = (TaskData)lvi.Tag;
                    StringBuilder t=new StringBuilder();
                    t.Append(td.taskname);
                    t.Append("┇┇");
                    t.Append(td.content);
                    t.Append("┇┇");
                    t.Append(td.enabled.ToString());
                    t.Append("┇┇");
                    t.Append(td.ex_setting);
                    t.Append("┇┇");
                    t.Append(td.IntervalTime.ToString());
                    t.Append("┇┇");
                    t.Append(td.RunTimes.ToString());
                    t.Append("┇┇");
                    t.Append(td.type.ToString());
                    sw.WriteLine(t.ToString());
                }
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();/**/
                MessageBox.Show("成功导出" + listView1.Items.Count + "条任务");
            }
        }
    }
}
